import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server {
    public static final List<Socket> sockets = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        // 监听本机指定端口
        ServerSocket ss = new ServerSocket(6666);

        // 每次获取到Client连接的时候, 创建一个新的线程, 来处理这个连接
        // 阻塞获取客户端的连接
        while (true) {
            // 每次建立连接的时候, 把Socket保存起来
            // 可以使用static属性, ArrayList保存
            Socket s = ss.accept();
            sockets.add(s);

            new ServerThread(s).start();
        }
    }
}

/*
读取client发送的内容,并且响应给所有的client
 */
class ServerThread extends Thread {
    private Socket socket;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            // 读取文件到内存
//            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

            while (true) {
                // 读的是一行数组, 要有换行才能是一行数据
                UserInfo userInfo = (UserInfo) ois.readObject();
//                String msg = br.readLine();

                String respMsg = userInfo.getName() + ": " + userInfo.getMsg();
                System.out.println(respMsg);
                // 需要写给所有的client, 每一个Clinet对应的是一个Socket
                for (Socket s : Server.sockets) {
                    PrintWriter pw = new PrintWriter(s.getOutputStream());
                    pw.println(respMsg);
                    pw.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

